using UnityEngine;

[RequireComponent(typeof(EnemyMovement))]
public class Enemy : MonoBehaviour
{
    [Header("Components")] 
    private EnemyMovement movement;
    
    [Header("Elements")] 
    private Player player;
    
    [Header("Spawn Sequence Related")]
    [SerializeField] private SpriteRenderer enemyRenderer;
    [SerializeField] private SpriteRenderer spawnRenderer;
    private bool hasSpawned;
    
    [Header("Effects")]
    [SerializeField] private ParticleSystem passAwayParticles;
    
    [Header("Attack")] 
    [SerializeField] private int damage;
    [SerializeField] private float attackFrequency;
    [SerializeField] private float playerDetectionRadius;

    [Header("Debug")] 
    [SerializeField] private bool gizmos;
    
    private float attackDelay;
    private float attackTimer;
    
    void Start()
    {
        movement = GetComponent<EnemyMovement>();
        player = FindFirstObjectByType<Player>();
        if (player == null)
        {
            Debug.LogWarning("未找到Player，将自动销毁...");
            Destroy(gameObject);
        }
        // 计算攻击延迟
        attackDelay = 1f / attackFrequency;
        StartSpawnSequence();
    }
    
    void Update()
    {
        // 尝试攻击玩家
        if (attackTimer >= attackDelay)
            TryAttack();
        else
            Wait();
    }

    private void StartSpawnSequence()
    {
        // 设置渲染器
        SetRenderersVisibility(false);
        
        // 设置动画
        var targetScale = spawnRenderer.transform.localScale * 1.2f;
        LeanTween.scale(spawnRenderer.gameObject, targetScale, 0.3f)
            .setLoopPingPong(4)
            .setOnComplete(SpawnSequenceCompleted);
        
    }
    
    private void SpawnSequenceCompleted()
    {
        // 设置渲染器
        SetRenderersVisibility(true);

        hasSpawned = true;
        movement.StorePlayer(player);
    }

    private void SetRenderersVisibility(bool visibility)
    {
        enemyRenderer.enabled = visibility;
        spawnRenderer.enabled = !visibility;
    }
    
    private void TryAttack()
    {
        float distanceToPlayer = Vector3.Distance(transform.position, player.transform.position);
        if (distanceToPlayer <= playerDetectionRadius)
        {
            Attack();
        }
    }

    private void Attack()
    {
        attackTimer = 0f;
        player.TakeDamage(damage);
    }
    
    private void Wait()
    {
        attackTimer += Time.deltaTime;
    }


    private void PassAway()
    {
        passAwayParticles.transform.SetParent(null);
        passAwayParticles.Play();
        
        Destroy(gameObject);
    }
    
    private void OnDrawGizmos()
    {
        if (!gizmos) return;
        
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, playerDetectionRadius);
    }
}
